from datetime import datetime

from django.shortcuts import render, redirect
from web.forms.project import ProjectModelForm
from django.http import JsonResponse, HttpResponse
from web import models
from utils.tencent.cos import create_bucket
from datetime import datetime

from web.views.issues import issues


def project_list(request):
    """项目列表"""
    if request.method == "GET":
        # 查询两次把此用户建立的和参与的分别查询出来。为了减少查询次数提高性能，分别循环查询出来的数据把对应的数据放在一个列表中
        # 带星标的存放时格式为：{'value':row,'type':'my'}、{'value':item.project,'type':'join'} ，其余的都按照正常存放
        project_dict = {"star":[],"my":[],"join":[]}
        my_project = models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project: # 带星标的放一起，用户建立的放一起，思路是不能重复放，也就是虽然都是此用户的建立的，但是带星标的和不带星标的分开存放
            if row.star:
                project_dict["star"].append({'value':row,'type':'my'})
                # project_dict["star"].append(row)
            else:
                project_dict["my"].append(row)
        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list: # 也是用上面的思路分。区别是不能把项目参与者这个对象放入字典中，要放入项目参与者外键连接的项目表的对象：item.project
            if item.star:
                project_dict["star"].append({'value':item.project,'type':'join'})
                # project_dict["star"].append(item.project)
            else:
                project_dict["join"].append(item.project)

        form = ProjectModelForm(request)
        return render(request,'web/project_list.html',{'form':form,"project_dict":project_dict})
    form = ProjectModelForm(request,data=request.POST)
    if form.is_valid():
        # 创建项目的同时，把存放项目文件的桶一起创建
        # current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        current_time = str(datetime.now().strftime("%Y%m%d-%H%M%S"))
        bucket = "{}-{}-1334110564".format(request.tracer.user.mobile_phone,current_time)
        region = 'ap-guangzhou'
        create_bucket(bucket,region)
        # 输入框中只有项目名、颜色、描述。所以还需要添加创建者creator。利用form的instance属性,把登录的用户对象赋值给form.instance.creator
        # 还需要在数据库中保存创建桶的信息，如：桶的名字和桶的区域
        form.instance.bucket = bucket
        form.instance.region = region
        form.instance.creator = request.tracer.user
        instance = form.save()

        # 创建项目时，初始化问题类型。循环项目类型表中的变量，并把项目和问题类型都存入到项目类型表中
        issues_type_object_list = []
        for item in models.IssuesType.PROJECT_INIT_LIST:
            issues_type_object_list.append(models.IssuesType(project=instance,title=item))
        # 循环完成后，通过bulk_create 来批量创建问题类型和对应的项目
        models.IssuesType.objects.bulk_create(issues_type_object_list)

        return JsonResponse({'status': True})
    return JsonResponse({'status':False,'error':form.errors})

def project_star(request,project_type,project_id):
    """星标项目"""
    # 判断参数project_type是我创建的：my，还是我参与的：join。
    # 前端的跳转链接的图案是星标，所以当点project_type == 'my'的项目中的星标时，会让项目表：Project表中的字段star的值等于true。
    # 点击project_type == 'join'项目中的星标时，会让表项目参与者表：ProjectUser 中的字段star的值等于true
    if project_type == 'my':
        models.Project.objects.filter(id=project_id,creator=request.tracer.user).update(star=True)
        return redirect('project_list')
    # 因为在参与表ProjectUser中的字段project是项目表的外键，外键未设置关联的列默认会以ID作为连接。所以project_id是跨表查询，直接跨到项目表的id
    # project_id=project_id即为跨表查询项目表对象的id跟传入的参数project_id作比较，若相等则点亮对应的星标
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id,user=request.tracer.user).update(star=True)
    # if project_type == 'star':
    #     models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
    #     models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
    #     return redirect('project_list')
    # return HttpResponse('请求错误')

def project_unstar(request,project_type,project_id):
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
        return redirect('project_list')
    return HttpResponse('请求错误')




